/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.ly.wxstore.service.account;

import java.util.Date;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ly.wxstore.comm.Delete;
import com.ly.wxstore.entity.Account;
import com.ly.wxstore.repository.AccountDao;
import com.ly.wxstore.service.WeixinUserInfoService;

/**
 * 用户管理类.
 * 
 * @author calvin
 */
// Spring Service Bean的标识.
@Component
@Transactional
public class AccountService {

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	@Autowired
	private WeixinUserInfoService weixinUserInfoService;
	
	@Autowired
	private AccountDao accountDao;

	public Account getByLoginName(String openid) {
		return accountDao.getByLoginName(openid);
	}

	/**
	 * 通过OAuth页面授权注册账号
	 * 
	 * @param openid
	 */
	public Account regiest(String openid) {
		logger.info("通过OAuth页面授权注册账号");
		Account account =  new Account();
		account.setCreateDate(new Date());
		account.setDeleted(Delete.Enabled);
		account.setLoginName(openid);
		account.setUid(UUID.randomUUID().toString());

		accountDao.save(account);
		
		return account;
	}

	/**
	 * 根据code读取微信UserInfo
	 * 
	 * @param code
	 * @return Openid
	 */
	public String receiveWeixinUserInfo(String code) {

		return weixinUserInfoService.receiveWeixinUserInfo(code);
	}

	public Long searchCount() {
		return accountDao.searchCount(null);
	}
}
